const ora = require("ora");
const { getRepoList, getTagList } = require("./https");
const inquirer = require("inquirer");
const downloadGitRepo = require("download-git-repo");
const path = require("path");

// 加载动画
async function wrapLoading(fn, message, ...args) {
  // 使用ora
  const spinner = ora(message);
  spinner.start();

  try {
    const result = await fn(...args);

    spinner.succeed();
    return result;
  } catch (err) {
    console.log(err);
    spinner.fail("Error message:", err.message);
  }
}

class Generator {
  name = ""; // 项目目录名称
  targetDir = ""; // 项目目录

  constructor(name, targetDir) {
    this.name = name;
    this.targetDir = targetDir;
  }

  // 从远端拉取仓库数据
  async getRepoList() {
    const repoList = await wrapLoading(getRepoList, "正在拉取模板...");
    if (!repoList) {
      return false;
    }

    // 选择模版
    const { repo } = await inquirer.prompt({
      name: "repo",
      type: "list",
      choices: repoList,
      message: "请选择项目模板",
    });

    return repo;
  }

  // 选择版本号
  async getTagList(repo) {
    // 基于选择 repo 的结果，查询对应tag列表
    const tags = await wrapLoading(getTagList, "正在拉取版本号...", repo);
    if (!tags) {
      return false;
    }

    const { tag } = await inquirer.prompt({
      name: "tag",
      type: "list",
      choices: tags,
      message: "请选择版本号",
    });

    return tag;
  }

  // 下载模板
  async download(repo, tag) {
    // 拼接下载地址

    const downloadUrl = `direct:https://gitee.com/keke111/${repo}.git#${tag}`;
    const dest = path.resolve(process.cwd(), this.targetDir);
    const spinner = ora("正在下载模板...");
    
    downloadGitRepo(downloadUrl, dest, { clone: true }, function (err) {
      if (err) {
        spinner.fail(err);
      } else {
        spinner.succeed();
        console.log(`\r\nSuccessfully created project`);
      }
    });
  }

  async create() {
    const repo = await this.getRepoList();
    const tag = await this.getTagList(repo);

    await this.download(repo, tag);
  }
}

module.exports = Generator;
